package com.study.netProtocol.http;

import sun.misc.IOUtils;

import java.io.IOException;
import java.io.InputStream;
import java.io.StringWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;
import java.util.Map;

/**
 * @author ysy
 * @version 1.0
 * @Title: HttpClient
 * @Note <b>ProjectName:</b> Pre-research
 * <br><b>PackageName:</b> com.study.netProtocol.http
 * <br><b>ClassName:</b>
 * <br><b>Date:</b>

 */
public class HttpClient {

    /**
     * 备注：本代码基于JDK8，JDK11提供了更简单易用的 HttpClient 客户端
     **/
    public static void main(String[] args) throws IOException {
        URL url = new URL("https://www.sina.com.cn/");
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("GET");
        conn.setUseCaches(false);
        // 请求超时5秒
        conn.setConnectTimeout(5000);
        // 设置HTTP头:
        conn.setRequestProperty("Accept", "*/*");
        conn.setRequestProperty("User-Agent", "Mozilla/5.0 (compatible; MSIE 11; Windows NT 5.1)");
        // 连接并发送HTTP请求:
        conn.connect();
        // 判断HTTP响应是否200:
        if (conn.getResponseCode() != 200) {
            throw new RuntimeException("bad response");
        }
        // 获取所有响应Header:
        Map<String, List<String>> map = conn.getHeaderFields();
        for (String key : map.keySet()) {
            System.out.println(key + ": " + map.get(key));
        }
        // 获取响应内容:
        InputStream input = conn.getInputStream();
        byte[] bytes = new byte[0];
        bytes = new byte[input.available()];
        input.read(bytes);
        String str = new String(bytes);
        System.out.println(str);
    }
}
